package com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.widget

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ScreenUtils
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ItemAttributeBinding
import com.vitabuybuy.tv.dto.GoodsDetailsDto
import com.library.common.base.BindRecycAdapter
import com.library.common.toast.XToast
import com.library.common.util.DensityUtil
import com.vitabuybuy.tv.adaptebinding.TextAdapter
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import kotlinx.android.synthetic.main.dialog_spec_selector.*
import java.util.regex.Pattern
import kotlin.math.roundToInt

/**
 * 作者：SimGa
 * 日期：2020/12/13
 * 时间：12:53
 * 包名：com.vitabuybuy.tv.dialog
 */
class LiveSpecSelectorDialog(context: Context) : Dialog(context, R.style.Dialog) {

    private val specAdapter by lazy { SpecAdapter() }
    private var valusList: List<GoodsDetailsDto.GoodsListBean>? = null
    private var stock = 0
    private var goodId = -1

    init {
        this.setCanceledOnTouchOutside(true)
        setContentView(R.layout.dialog_spec_selector)
        val window = window
        window!!.setGravity(Gravity.BOTTOM) // 此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.bottom_int_out_dialog_style) // 添加动画
        val dm = DisplayMetrics()
        window.windowManager.defaultDisplay.getMetrics(dm)
        window.setLayout(dm.widthPixels, (ScreenUtils.getScreenHeight() * 3.5 / 5).roundToInt())
        window.setBackgroundDrawable(ColorDrawable(0x00000000))

        rcvAttribute.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = specAdapter
        }
        specAdapter.onItemClick = {
            val ids = ArrayList<Int>()
            if (it.size == specAdapter.mData.size) {
                for (map in it) {
                    for (set in map.value) {
                        ids.add(specAdapter.mData[map.key].valueList[set].id)
                    }
                }
                ids.sort()
                var code = ""
                for (set in ids) {
                    code = "$code${set}-"
                }
                code = Pattern.compile("\\-+$").matcher(code).replaceAll("")
                for (good in valusList!!) {
                    if (code == good.code) {
                        if (good.image != null) {
                            ImageAdapter.setNomalImageUrl(
                                ivImage,
                                good.image,
                                ContextCompat.getDrawable(context, R.drawable.default_image)
                            )
                        }
                        TextAdapter.setNowPrice(
                            tvPrice,
                            good.livePrice
                        )
                        goodId = good.id
                        stock = good.liveQuantity
                        tvStock.visibility = View.VISIBLE
                        TextAdapter.setStockTextView(tvStock, stock)
                        if (stock == 0) tvQuantity.text = "0" else tvQuantity.text = "1"
                        break
                    }
                }
            }
        }
        btnAddToShoppingCart.visibility = View.GONE
        ivClose.setOnClickListener { dismiss() }
        ivMinus.setOnClickListener {
            var buyNum = tvQuantity.text.toString().toInt()
            if (buyNum == 1) {
                return@setOnClickListener
            }
            buyNum--
            tvQuantity.text = buyNum.toString()
        }
        ivAdd.setOnClickListener {
            var buyNum = tvQuantity.text.toString().toInt()
            if (buyNum == stock) {
                return@setOnClickListener
            }
            buyNum++
            tvQuantity.text = buyNum.toString()
        }
        btnBuyNow.setOnClickListener {
            if (goodId == -1) {
                XToast.normal(context.getString(R.string.please_choose_commodity_specification))
                return@setOnClickListener
            }
            if (tvQuantity.text.toString().toInt() == 0) {
                XToast.normal(context.getString(R.string.this_goods_stock_is_zreo))
                return@setOnClickListener
            }
            onbuyNowClick(goodId, tvQuantity.text.toString().toInt())
            dismiss()
        }
    }

    lateinit var onbuyNowClick: (goodId: Int, buyNum: Int) -> Unit

    fun setSpecDatas(
        list: List<GoodsDetailsDto.AttributeListBean>,
        valusList: List<GoodsDetailsDto.GoodsListBean>,
        livePrice: Double,
        image: String
    ) {
        goodId = -1
        specAdapter.setNewData(list)
        this.valusList = valusList
        ImageAdapter.setNomalImageUrl(
            ivImage,
            image,
            ContextCompat.getDrawable(context, R.drawable.default_image)
        )
        TextAdapter.setNowPrice(tvPrice, livePrice)
    }

    class SpecAdapter :
        BindRecycAdapter<ItemAttributeBinding, GoodsDetailsDto.AttributeListBean>() {
        var selectedMap = HashMap<Int, Set<Int>>()
        override fun onBindViewHolder(
            mBinding: ItemAttributeBinding,
            itemData: GoodsDetailsDto.AttributeListBean,
            holder: RecyclerView.ViewHolder,
            position: Int
        ) {
            mBinding.tvValueName.text = itemData.name
            mBinding.tagLayout.adapter = object :
                TagAdapter<GoodsDetailsDto.AttributeListBean.ValueListBean>(itemData.valueList) {
                override fun getView(
                    parent: FlowLayout,
                    position: Int,
                    str: GoodsDetailsDto.AttributeListBean.ValueListBean
                ): View {
                    val tvTip = LayoutInflater.from(mContext).inflate(
                        R.layout.item_att,
                        mBinding.tagLayout, false
                    ) as TextView
                    tvTip.text = str.text
                    val ll = tvTip.layoutParams as ViewGroup.MarginLayoutParams
                    ll.rightMargin = DensityUtil.dip2px(20f)
                    ll.bottomMargin = DensityUtil.dip2px(20f)
                    tvTip.layoutParams = ll
                    return tvTip
                }
            }
            mBinding.tagLayout.setOnSelectListener {
                if (it.isEmpty()) {
                    selectedMap.remove(position)
                } else {
                    selectedMap[position] = it
                }
                onItemClick(selectedMap)
            }
        }

        override fun normalViewId(viewType: Int): Int {
            return R.layout.item_attribute
        }

        lateinit var onItemClick: (selectedMap: HashMap<Int, Set<Int>>) -> Unit
    }
}